<script>
//数据表预览模块
import SheetLoader from '@/utils/sheet-loader';

export default {
  name: 'DataTableViewer',
  props: {
    //数据ID
    dataId: {
      type: String,
      default() {
        return '';
      },
    },
  },
  data() {
    return {
      //数据加载器
      sheetLoader: null,
      //记录总数
      totalCount: 0,
      //分页大小
      pageSize: 10,
      //表格列
      columns: [],
      //分页数据
      pagedData: [],
      //数据标题
      title: '',
    };
  },
  //初始化表格
  async mounted() {
    this.sheetLoader = new SheetLoader(this.dataId);
    const response = await this.sheetLoader.getPagedData(1, this.pageSize);
    this.totalCount = this.sheetLoader.data.length;
    this.title = `预览 "${this.sheetLoader.dataInfo.name}" 数据表`;
    this.columns = Object.keys(response[0] || {}).map(p => {
      return { title: p, key: p, ellipsis: true };
    });
    this.pagedData = response;
    this.$emit('dataLoaded', {
      title: this.title,
      data: this.sheetLoader.data,
    });
  },
  methods: {
    //获取分页数据
    async getPagedData(pageIndex) {
      this.pagedData = await this.sheetLoader.getPagedData(pageIndex, this.pageSize);
    },
    //导出数据
    exportData() {
      this.$refs.viewTable.exportCsv({
        filename: this.sheetLoader.dataInfo.name,
        columns: this.columns,
        data: this.sheetLoader.data,
      });
    },
  },
};
</script>

<template>
  <div class="table-viewer-wrapper">
    <Table
      ref="viewTable"
      :height="500"
      :columns="columns"
      :data="pagedData"
      border
      stripe
    >
    </Table>
    <Page
      v-if="totalCount > pageSize"
      :total="totalCount"
      :page-size="pageSize"
      @on-change="getPagedData"
    >
    </Page>
  </div>
</template>

<style lang="less">
.table-viewer-wrapper {
  .k-page {
    margin-top: 10px;
    text-align: right;
  }
}
</style>
